package cn.adelyn.base.auth.controller;

import cn.adelyn.base.api.auth.pojo.bo.UserInfoInTokenBO;
import cn.adelyn.base.auth.pojo.dto.AuthenticationDTO;
import cn.adelyn.base.auth.pojo.dto.LogoutDTO;
import cn.adelyn.base.auth.pojo.vo.TokenInfoVO;
import cn.adelyn.base.auth.service.AuthAccountService;
import cn.adelyn.base.auth.service.TokenService;
import cn.adelyn.base.secureweb.AuthUserContext;
import cn.adelyn.common.core.response.ServerResponseEntity;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author chengze
 * @date 2022/12/20
 * @desc 登录接口
 */
@RestController
public class LoginController {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private AuthAccountService authAccountService;


	@PostMapping("/login")
	public ServerResponseEntity<TokenInfoVO> login(@Valid @RequestBody AuthenticationDTO authenticationDTO) {

		UserInfoInTokenBO userInfoInTokenBO = authAccountService
				.getUserInfoInTokenByInputUserNameAndPassword(authenticationDTO.getPrincipal(),
						authenticationDTO.getCredentials());

		// 保存token，返回token数据给前端，这里是最重要的
		return ServerResponseEntity.success(tokenService.genAndStoreTokenPair(userInfoInTokenBO));
	}

	@PostMapping("/logout")
	public ServerResponseEntity loginOut(@Valid @RequestBody LogoutDTO logoutDTO) {
		UserInfoInTokenBO userInfoInTokenBO = AuthUserContext.get();
		tokenService.delTokenPair(userInfoInTokenBO.getUserType(), userInfoInTokenBO.getUserId(),
				logoutDTO.getRefreshToken());
		// 删除该用户在一台设备的token
		return ServerResponseEntity.success();
	}

}
